package com.example.order_product.Service.impl;

import com.example.order_product.Entity.Order;
import com.example.order_product.Entity.Product;
import com.example.order_product.Mapper.OrderMapper;
import com.example.order_product.Mapper.ProductMapper;
import com.example.order_product.Service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceimpl implements OrderService {
    private final OrderMapper orderMapper;

    private final ProductMapper productMapper;

    public OrderServiceimpl(OrderMapper orderMapper, ProductMapper productMapper) {
        this.orderMapper = orderMapper;
        this.productMapper = productMapper;
    }

    @Override
    public void addOrder(Order order, Product product) {
        double TotalPrice = (double) order.getQuantity() * product.getPrice();
        order.setTotalPrice(TotalPrice);
        order.setOrderDate(new Date());
        order.setStatus("待发货");
        orderMapper.insert(order);
    }

    @Override
    public boolean judgeStock(Order order, Product product) {
        Integer quantity = order.getQuantity();
        Integer stock = product.getStock();
        return stock < quantity;
    }

    @Override
    public Order findOrderByid(int id) {
        Order order = orderMapper.selectById(id);
        return order;
    }

    @Override
    @Transactional
    public void updateOrderStatus(Order order) {
        Product product = productMapper.selectById(order.getProductId());
        Integer now_stock = product.getStock() - order.getQuantity();
        product.setStock(now_stock);
        productMapper.updateById(product);

        order.setStatus("已完成");
        orderMapper.updateById(order);
    }


}

